package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.config.CacheService;
import com.heima.article.service.ApArticleBehaviorService;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.behavior.dtos.BehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thread.BhThreadLocalUtil;
import thread.WmThreadLocalUtil;

@Service
@Slf4j
public class ApArticleBehaviorServiceImpl implements ApArticleBehaviorService {

    private final CacheService cacheService;

    public ApArticleBehaviorServiceImpl(CacheService cacheService) {
        this.cacheService = cacheService;
    }

    @Override
    public ResponseResult articleBehavior(ArticleInfoDto articleInfoDto) {
        //获取userid和articleid来生成键
        Long articleId = articleInfoDto.getArticleId();
        Integer userId;

        ApUser user = BhThreadLocalUtil.getUser();
        userId = user.getId();

        if (userId != null) {
            //redis的key
            String key = userId + "-" + articleId;

            //redis是否存在对应的key

            Boolean exists = cacheService.exists(key);
            if (exists){

                String redisKey = cacheService.get(key);
                ResponseResult<Object> result = new ResponseResult<>();
                BehaviorDto behaviorDto = JSON.parseObject(redisKey, BehaviorDto.class);
                result.setData(behaviorDto);
                result.setCode(200);
                result.setErrorMessage("操作成功");
                result.setHost(null);
                return result;
            }else {
                ResponseResult<Object> result = new ResponseResult<>();
                BehaviorDto behaviorDto = new BehaviorDto();
                result.setData(behaviorDto);
                result.setCode(200);
                result.setErrorMessage("没有在redis中存在，返回默认值");
                result.setHost(null);
                return result;
            }
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }
}